import preferences from '@ohos.data.preferences';
class PreferencesUtil{
  //方式1：pref:preferences.Preferences
  //方式2：通过键值对存储信息
  prefMap:Map<string,preferences.Preferences> = new Map()
  async loadPreference(context,name:string){
    try {
      let pref = await preferences.getPreferences(context, name) //同步调用。直接拿到数据
      this.prefMap.set(name, pref)
      console.log('存储token成功!')
    } catch (e) {
      console.log('存储token失败!')
    }
        // preferences.getPreferences(context,name)//返回值是一个promise
        //   .then(pref => {
        //     //方式1：this.pref = pref
        //     //方式2：
        //     this.prefMap.set(name,pref)
        //     console.log('存储token成功!')
        //   })
        //   .catch(reason => {
        //     console.log('存储token失败!')
        //   })
      }
  //存储：
  async  putPreferenceValue(name:string,key:string,value:preferences.ValueType){
    if(!this.prefMap.has(name)){
      console.log('写入操作失败，preference尚未初始化!')
      return
    }
    try {
      let pref = this.prefMap.get(name)
      //写入数据
      await pref.put(key, value)
      //写入磁盘
      await pref.flush()
      console.log('token存入磁盘成功!')
    } catch (e) {
      console.log('token存入磁盘失败!'+JSON.stringify(e))
    }
  }

  //读取
  async getPreferenceValue(name:string,key:string,defaultValue:preferences.ValueType){
    if(!this.prefMap.has(name)){//判断是否有值，没有值提示没有初始化
      console.log('读取操作失败，preference尚未初始化!')
      return
    }
    try {
      let pref = this.prefMap.get(name)
      //读取数据
      return await pref.get(key, defaultValue)
      console.log('读取token成功!')
    } catch (e) {
      console.log('读取token失败!'+JSON.stringify(e))
    }
  }
}

const preferencesUtil = new PreferencesUtil();
export default preferencesUtil as PreferencesUtil